# 部署测试脚本 - 验证Docker环境并启动项目容器

Write-Host "===== 七夕浪漫网站部署测试 ====="

# 检查Docker是否已安装
Write-Host "`n1. 检查Docker是否已安装..."
try {
    $dockerVersion = docker --version
    Write-Host "✅ Docker已安装: $dockerVersion"
} catch {
    Write-Host "❌ 错误: 未找到Docker。请先安装Docker。"
    Write-Host "   下载地址: https://docs.docker.com/get-docker/"
    exit 1
}

# 检查Docker Compose是否已安装
Write-Host "`n2. 检查Docker Compose是否已安装..."
try {
    $dockerComposeVersion = docker-compose --version
    Write-Host "✅ Docker Compose已安装: $dockerComposeVersion"
} catch {
    Write-Host "❌ 错误: 未找到Docker Compose。请先安装Docker Compose。"
    Write-Host "   下载地址: https://docs.docker.com/compose/install/"
    exit 1
}

# 检查项目文件是否完整
Write-Host "`n3. 检查项目文件是否完整..."
$requiredFiles = @("Dockerfile", "docker-compose.yml", "nginx.conf", "index.html", "qixi.html")
$missingFiles = @()

foreach ($file in $requiredFiles) {
    if (-Not (Test-Path $file)) {
        $missingFiles += $file
    }
}

if ($missingFiles.Count -gt 0) {
    Write-Host "❌ 错误: 缺少以下必要文件:"
    foreach ($file in $missingFiles) {
        Write-Host "   - $file"
    }
    exit 1
} else {
    Write-Host "✅ 所有必要文件都已找到"
}

# 检查assets目录
Write-Host "`n4. 检查assets目录..."
if (-Not (Test-Path "assets" -PathType Container)) {
    Write-Host "❌ 错误: 未找到assets目录"
    exit 1
} else {
    Write-Host "✅ assets目录已找到"
}

# 停止并移除旧容器（如果存在）
Write-Host "`n5. 清理旧容器（如果存在）..."
docker-compose down 2>$null

# 如果仍有冲突的容器，强制移除它
$conflictingContainers = @("morning-quote-app", "qixi-romantic-app")
foreach ($container in $conflictingContainers) {
    $containerExists = docker ps -a -q -f "name=$container"
    if ($containerExists) {
        Write-Host "   正在移除冲突的容器: $container"
        docker rm -f $container 2>$null
    }
}

Write-Host "✅ 清理完成"

# 构建并启动新容器
Write-Host "`n6. 构建并启动容器..."
docker-compose up -d --build

if ($LASTEXITCODE -eq 0) {
    Write-Host "✅ 容器构建并启动成功！"
    
    # 显示容器状态
    Write-Host "`n7. 容器状态:"
    docker-compose ps
    
    Write-Host "`n===== 部署测试完成 ====="
    Write-Host "🎉 网站已成功部署！"
    Write-Host "📌 主页面访问地址: http://localhost/"
    Write-Host "📌 七夕浪漫页面访问地址: http://localhost/qixi.html"
    Write-Host "`n🔧 如需查看容器日志，请运行: docker-compose logs -f"
    Write-Host "🔧 如需停止容器，请运行: docker-compose down"
} else {
    Write-Host "❌ 容器构建或启动失败！"
    Write-Host "   请查看上面的错误信息了解详情。"
    exit 1
}